<template>
  <div class="video-wrapper">
    <a-upload
      :drag="true"
      list-type="picture-card"
      class="avatar-uploader"
      :show-file-list="false"
      :before-upload="onBeforeUpload"
      :custom-request="DoUpload"
      @change="handleChange"
    >
      <div class="video-block">
        <p class="upload-text">点击或将文件拖拽到这里上传</p>
        <p class="upload-hint">支持扩展名 mp4、mkv、mpeg、avi、navi、asf、mov ...</p>
      </div>
    </a-upload>
    <div v-for="(item, index) in fileList" :key="index">
      <span class="file-icon">[文件]</span>
      <span style="margin: 0 10px;">{{ item.name }}</span>
      <a-button type="text" status="danger" @click="handleDelete(item.uid)">删除</a-button>
    </div>
  </div>
</template>
<script>
import { Message } from '@arco-design/web-vue'
import { typeMap } from '@/common/constant'

// 格式与大小校验
const beforeUploadFile = (file) => {
	const isVideo = file.type === 'video/mp4' || file.type === 'video/mkv' || file.type === 'video/mpeg' || file.type === 'video/avi' || file.type === 'video/navi' || file.type === 'video/asf' || file.type === 'video/mov'
  if (!isVideo) {
    Message.info('视频格式不支持')
  }
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    Message.info('视频大小超过 50M!')
  }
  return isVideo && isLt50M
}

export default {
  name: 'UploadVideo',
  props: {
    single: {
      type: Boolean,
      default: true
    },
    value: {
      type: String,
      default: ''
    },
    params: {
      type: Object,
      default: function () {
        return {
          busType: typeMap.article
        }
      }
    }
  },
  data () {
    return {
      loading: false,
      file: null,
      fileList: []
    }
  },
  watch: {
    value: {
      handler (val) {
        this.path = val || ''
      },
      immediate: true
    }
  },
  methods: {
    handleChange (e) {
      this.fileList = e.fileList || []
    },
    handleDelete (uid) {
      this.fileList.splice(this.fileList.findIndex(item => item.uid === uid), 1)
    },
    onBeforeUpload (file) {
			this.file = file
      return beforeUploadFile(file)
    },
    async DoUpload () {
      const _this = this
      const { params, $http } = _this
      _this.loading = true
      const formdata = new FormData()
      formdata.append('file', _this.file)
      for (const key in params) {
        formdata.append(key, params[key])
      }
      _this.loading = false
      try {
        const { result } = await $http.post('/file/upload', formdata, {
          'Content-Type': 'multipart/form-data'
        })
        _this.$emit('ok', result)
      } catch (error) {
        console.log('/file/upload:', error)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.video-wrapper{
  width: 400px;
	height: auto;
}
.video-block{
	width: 400px;
	height: auto;
}
</style>
